package cn.cxq.learning.circle_array_queue;

/**
 *  数组模拟环形队列
 */
public class CircleArrayQueue {

    private int maxSize;
    private int[] arr;
    private int front;
    private int rear;

    /**
     * 由于这种初始化的方式，导致队列的容量为maxsize-1
     * @param maxSize
     */
    public CircleArrayQueue(int maxSize) {
        this.maxSize = maxSize;
        this.arr = new int[this.maxSize];
        this.front = 0;  //指向数组的第一个数的位置
        this.rear = 0;  //指向数组的最后一个数的后一个位置
    }

    public boolean isEmpty(){
        return this.front == this.rear;
    }

    public boolean isFull(){
        return (this.rear + 1 - this.maxSize)%this.maxSize == this.front;
    }

    public void add(int value){
        if (isFull()){
            System.out.println("队列已满，无法加入数据~~~");
            return;
        }
        this.arr[rear] = value;
        this.rear = (this.rear + 1) % this.maxSize;
    }

    public int get(){
        if (isEmpty()){
            throw new RuntimeException("队列为空，无法取值~~~");
        }
        int result = this.arr[this.front];
        this.front = (this.front + 1) % this.maxSize;
        return result;
    }

    public int getFront(){
        if (isEmpty()){
            throw new RuntimeException("队列为空，无法取值~~~");
        }

        return this.arr[this.front];
    }

    public void showQueue(){
        if (isEmpty()){
            System.out.println("队列为空~~~");
            return;
        }
        for (int i = 0; i < size(); i++) {
            System.out.printf("arr[%d]=[%d]\n",(this.front+i)%this.maxSize, arr[(this.front+i)%this.maxSize]);
        }
    }

    public int size(){
        return (this.rear + this.maxSize - this.front) % this.maxSize;
    }
}
